package com.example.util;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.common.ConstantConfig;
import com.example.common.ObjectUtils;
import com.univocity.parsers.csv.CsvWriter;
import com.univocity.parsers.csv.CsvWriterSettings;

@Component
public class ExportCVSUtil {
	
	@Autowired
	private ConstantConfig constantConfig;
	
	/** 
	*
	* @param title      标题
	* @param headNames  头部
	* @param keys       
	* @param valueList
	* @param path
	* @return File
	* @author liuhuaqing
	 * @throws IOException 
	* @date 2018年7月28日上午11:49:33
	*/ 
	public  String createCSVFileURL(String title,List<String> headNames, List<String> keys,List<Map> valueList, String path) throws IOException
	{
		//将List<String> keys 和 List<Map> valueList 转换为 List<List<String>> dataList
		List<List<Object>> dataList =new ArrayList<>();
		for(Map item:valueList)
		{
			List<Object> rowData=new ArrayList<>();
			for(String key:keys)
			{
				if(item.get(key) instanceof String)
				{
					rowData.add(item.get(key).toString()+"\t");
				}else
				{
					rowData.add(item.get(key));
				}
				
			}
			dataList.add(rowData);
		}
		
		//真实的输出目录
		String trueFileName=getTrueFileName(title);
		String outPut=getFilePath(path, trueFileName);
		createCSVFile(headNames, dataList, outPut);
		return constantConfig.getConfig("excelDown") + trueFileName;
		
	}
	
	
	public  String createCSVFilePath(String title,List<String> headNames, List<String> keys,List<Map> valueList, String path) throws IOException
	{
		//将List<String> keys 和 List<Map> valueList 转换为 List<List<String>> dataList
		List<List<Object>> dataList =new ArrayList<>();
		for(Map item:valueList)
		{
			List<Object> rowData=new ArrayList<>();
			for(String key:keys)
			{
				if(item.get(key) instanceof String)
				{
					String str=(String) item.get(key);
					rowData.add(str+"\t");
				}else
				{
					rowData.add(item.get(key));
				}
				
			}
			dataList.add(rowData);
		}
		
		//真实的输出目录
		String trueFileName=getTrueFileName(title);
		String outPut=getFilePath(path, trueFileName);
		createCSVFile(headNames, dataList, outPut);
		return constantConfig.getConfig("excelPath") + trueFileName;
		
	}
	
	public  File createCSVFile(List<String> head, List<List<Object>> dataList,String outPutPath) throws IOException {
			File csvFile = null;
		try {
			// 1. 创建文件
			csvFile = new File(outPutPath);
			//csvFile = new File(outPutPath + File.separator + filename + ".csv");
			File parent = csvFile.getParentFile();
			if (parent != null && !parent.exists()) {
			parent.mkdirs();
			}
			csvFile.createNewFile();
			
			
			
			
			
			// ===========  2. 写出CSV文件     ============//
			CsvWriterSettings writerSettings = new CsvWriterSettings();
			writerSettings.setHeaderWritingEnabled(true);
			writerSettings.setIgnoreLeadingWhitespaces(false);
			writerSettings.setIgnoreTrailingWhitespaces(false);

			String[] array=new String[head.size()];
			head.toArray(array);
			writerSettings.setHeaders(array);
			
			CsvWriter writer=new CsvWriter(csvFile, "GB2312", writerSettings);
			//CsvWriter writer = new CsvWriter(new FileWriter(csvFile), writerSettings);
			writer.writeRowsAndClose(dataList);
			
			
			/*System.out.println("file length"+csvFile.length());
			//按UCS规范 传输字符"ZERO WIDTH NO-BREAK SPACE"
			FileUtil.writeHead(csvFile, new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF });
			System.out.println("file length after write head "+csvFile.length());*/
			
		} catch (IOException e) {
			
			System.out.println("export csv file Failed .erro:"+e.getMessage());
			throw e;
		}
			System.out.println("export csv file success ，file path:"+csvFile.getAbsolutePath());
			return csvFile;
		
		}
	
	
	public static void main(String[] args) {
		SortedMap<String, Charset> map=Charset.availableCharsets();
		System.out.println(map);
	}
	
	private String getTrueFileName(String fileName)
	{
		return  String.valueOf(System.currentTimeMillis()) + "_"+fileName+".csv"; 
	}
	
	private  String getFilePath(String path,String trueFileName)
	{
		if(ObjectUtils.isEmpty(path)){
    		return constantConfig.getConfig("excelPath")+ trueFileName;  
    	}else{
    		return path+trueFileName; 
    	}
	}
}
